<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="需求明细">
            <PageableTable
              :loading="false"
              :table-height="200"
              :data="formItem.recipientRequires"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in insideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="150">
                <template slot-scope="{row}">
                  <el-button type="text" size="mini" icon="el-icon-search" title="查询" @click="search(row)">查询</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分配明细">
            <PageableTable
              :loading="false"
              :table-height="200"
              :data="formItem.lingyong"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in insideColumns2" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column v-if="formItem.categories === '3'" label="配发数量" header-align="center" align="center">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.lingyongQuantity" :min="1" size="mini" :precision="0" :max="scope.row.amount" />
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center">
                <template slot-scope="{row}">
                  <el-button type="text" size="mini" icon="el-icon-delete" title="删除" @click="remove(row)">删除</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="">
            <el-button size="mini" @click="btnCancel">取 消</el-button>
            <el-button type="primary" @click="commit">提 交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog title="选择资产" :append-to-body="true" :show="assetDialogFormVisible" @on-ok="selectOk" @on-cancel="assetDialogFormVisible = false">
      <div v-if="assetDialogFormVisible">
        <assets
          v-if="formItem.categories !=='4'"
          ref="assets"
          :locked="false"
          :status-search-show="false"
          status="unused"
          belongs="kj"
          :for-selection="true"
          :categories="formItem.categories"
          :small-type-code="selectTypeCode"
          :type-search-show="false"
          :specifications="selectSpecifications"
        />
        <goodsFile
          v-if="formItem.categories ==='4'"
          ref="goodsFile"
          :sparetypecode="selectTypeCode"
          :specification="selectSpecifications"
          :for-selection="true"
          :showtype="false"
        />
      </div>
    </SelectDialog>
  </div>
</template>
<script>
import { confirmCreate as create, confirmDetail as detail } from '@neu/dcam-ui/api/lingyongKJ'
import PageableTable from '@neu/biz-core/components/PageableTable'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import assets from '@neu/dcam-ui/views/fixedAsset/tables'
import goodsFile from '@neu/dcam-ui/views/goodsFile/tables'
const formItem = {
  title: '',
  reason: '',
  remark: '',
  categories: '',
  comprehensive: true,
  recipientRequires: [],
  createUser: '',
  orgCode: '',
  orgName: '',
  lingyong: []
}

export default {
  components: {
    PageableTable,
    SelectDialog,
    assets,
    goodsFile
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      assetDialogFormVisible: false,
      formItem: { ...formItem },
      insideColumns: [
        { title: '资产分类', width: 300, key: 'type',
          render: (h, params) => {
            let txt = params.row.smallTypeName
            if (params.row.middleTypeName) {
              txt = params.row.middleTypeName + ' / ' + txt
            }
            if (params.row.bigTypeName) {
              txt = params.row.bigTypeName + ' / ' + txt
            }
            return h('span', txt)
          }
        },
        { title: '规格型号', width: 100, key: 'specifications' },
        { title: '需求明细', width: 100, key: 'detail' },
        { title: '数量', width: 100, key: 'quantity' }
      ],
      insideColumns2: [
        { title: '名称', key: 'name', display: true },
        { title: '资产编号', key: 'code', display: true },
        { title: '资产分类', width: 300, key: 'type',
          render: (h, params) => {
            let txt = params.row.smallTypeName
            if (params.row.middleTypeName) {
              txt = params.row.middleTypeName + ' / ' + txt
            }
            if (params.row.bigTypeName) {
              txt = params.row.bigTypeName + ' / ' + txt
            }
            return h('span', txt)
          }
        },
        { title: '规格型号', key: 'specifications', display: true },
        { title: '序列号', key: 'serialnumber', display: true }
      ],
      rules: {},
      selectTypeCode: '',
      selectSpecifications: ''
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          // 消耗品的时候隐藏分类
          if (response.data.categories === '3' || response.data.categories === '4') {
            const hiddenColumns = ['bigTypeName', 'middleTypeName', 'serialnumber', 'code']
            this.insideColumns = this.insideColumns.filter(l => !hiddenColumns.includes(l.key))
            this.insideColumns2 = this.insideColumns2.filter(l => !hiddenColumns.includes(l.key))
          }

          this.formItem = {
            ...response.data
          }
        })
      }
    },
    search(row) {
      this.selectTypeCode = row.smallTypeCode
      // this.selectSpecifications = row.specifications
      this.assetDialogFormVisible = true
    },
    selectOk() {
      if (this.formItem.categories === '4') {
        const assets = this.$refs.goodsFile.selections
        const assetCodes = this.formItem.lingyong.map(a => a.code)
        const difference = assets.filter(t => {
          return !assetCodes.includes(t.code)
        })
        difference.forEach(element => {
          this.formItem.lingyong.push({ 'name': element.name, 'code': element.code, 'lingyongQuantity': 1, 'specifications': element.specification, 'smallTypeName': element.spareTypeName, 'smallTypeCode': element.spareTypeCode })
        })
      } else {
        const assets = this.$refs.assets.selections
        const assetCodes = this.formItem.lingyong.map(a => a.code)
        const difference = assets.filter(t => {
          return !assetCodes.includes(t.code)
        })
        difference.forEach(element => {
          this.formItem.lingyong.push({ ...element, 'lingyongQuantity': 1 })
        })
      }
      this.assetDialogFormVisible = false
      this.selectTypeCode = null
      this.selectSpecifications = null
    },
    commit() {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          let num = 0
          this.formItem.recipientRequires.forEach(l => {
            num += l.quantity
          })
          let peifaNum = 0
          if (this.formItem.categories === '3') {
            peifaNum = this.formItem.lingyong.reduce(function(total, currentValue, currentIndex, arr) {
              return total + currentValue.lingyongQuantity
            }, 0)
          } else {
            peifaNum = this.formItem.lingyong.length
          }

          if (peifaNum !== num) {
            return this.$message({
              showClose: true,
              message: '配发资产不符合要求!',
              type: 'error'
            })
          }

          const data = []

          this.formItem.lingyong.forEach(l => {
            const item = { ...l }
            item.workOrderNum = this.workOrderNum
            item.taskId = this.taskId
            item.managementOrgName = this.formItem.orgName
            item.managementOrgCode = this.formItem.orgCode
            data.push(item)
          })
          // ge.x 2022-04-08 增加锁屏功能
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          create(data).then(res => {
            if (res.status === 'success') {
              loading.close()
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          }).catch(() => {
            loading.close()
            this.$emit('cancelNewOrderForm', 'refresh')
          })
        }
      })
    },
    /** 移除一条数据 */
    remove(row) {
      const i = this.formItem.lingyong.lastIndexOf(row)
      this.formItem.lingyong.splice(i, 1)
    },
    btnCancel() {
      this.$emit('cancelNewOrderForm', 'refresh')
    }
  }
}
</script>
